<template>
    <span :endTime="endTime" :endText="endText" :style="{color:color?color:'#909399'}">
        <slot>
            {{content}}
        </slot>
    </span>
</template>
<script>
export default {
    data () {
        return {
            content: '',
            color: ''
        }
    },
    props: {
        endTime: {
            type: String,
            default: ''
        },
        endText: {
            type: String,
            default: '已结束'
        }
    },
    mounted () {
        this.countdowm(this.endTime)
    },
    methods: {
        dateToLong (dateStr) {
            if (!dateStr) {
                return 0
            }
            return new Date(dateStr.replace(/-/g, '/')).getTime()
        },
        countdowm (timestamp) {
            console.log(timestamp)
            let self = this
            // if (!this.endTime){
            //   return
            // }

            let timer = setInterval(() => {
                let nowTime = new Date().getTime()
                let endTime = this.dateToLong(this.endTime)
                let t = endTime - nowTime
                if (t > 0) {
                    let day = Math.floor(t / 86400000)
                    let hour = Math.floor((t / 3600000) % 24)
                    let min = Math.floor((t / 60000) % 60)
                    let sec = Math.floor((t / 1000) % 60)
                    hour = hour < 10 ? '0' + hour : hour
                    min = min < 10 ? '0' + min : min
                    sec = sec < 10 ? '0' + sec : sec
                    let format = ''
                    if (day > 0) {
                        format = `${day} 天 ${hour} 小时 ${min} 分钟 ${sec} 秒`
                    }
                    if (day <= 0 && hour > 0) {
                        format = `${hour} 小时 ${min} 分钟 ${sec}秒`
                    }
                    if (day <= 0 && hour <= 0) {
                        format = `${min} 分钟 ${sec} 秒`
                    }
                    if (min <= 0) {
                        self.color = '#ff3333'
                    }
                    self.content = format
                } else if (this.endTime) {
                    clearInterval(timer)
                    self.content = self.endText
                    this.$emit('callback')
                }
            }, 1000)
        }
    }
}
</script>
